<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2023/9/18
 * Time: 17:12
 */

namespace app\admin\controller;

use think\Db;
use think\Request;

class Bigmember extends Base
{
    /**
     * 家大业大用户列表
     * @return mixed|\think\response\Json
     */
    public function index(){
        if(request()->isAjax ()){
            $keyword = trim(input('keyword'), ' '); // 用户ID/手机号/姓名/昵称
            $user_gender = input('user_gender'); // 性别   1 男   2 女   3 未知
            $user_sheng = input('user_sheng');
            $user_shi = input('user_shi');
            $user_qu = input('user_qu');
            $start_time = input('start_time'); // 注册开始时间
            $end_time = input('end_time'); // 注册结束时间
            $login_start_time = input('login_start_time'); // 登录开始时间
            $login_end_time = input('login_end_time'); // 登录结束时间

            $where['user_big_rule'] = 1;
            $where['user_status'] = ['NEQ', 3];
            $where['user_private_worker'] = 1;
            // 关键字
            if(isset($keyword) && $keyword != ''){
                $where['user_id|user_phone|user_username|user_real_name'] = ['like', '%' . $keyword . '%'];
            }
            // 性别
            if(isset($user_gender) && $user_gender != ''){
                $where['user_gender'] = $user_gender;
            }
            // 省
            if(isset($user_sheng) && $user_sheng != ''){
                $where['user_sheng'] = $user_sheng;
            }
            // 市
            if(isset($user_shi) && $user_shi != ''){
                $where['user_shi'] = $user_shi;
            }
            // 区
            if(isset($user_qu) && $user_qu != ''){
                $where['user_qu'] = $user_qu;
            }
            // 注册时间
            if(isset($start_time) && $start_time != '' && isset($end_time) && $end_time != ''){
                $where['user_time'] = ['between', [$start_time, $end_time]];
            }
            if(isset($start_time) && $start_time != '' && isset($end_time) && $end_time == ''){
                $where['user_time'] = ['>=', $start_time];
            }
            if(isset($start_time) && $start_time == '' && isset($end_time) && $end_time != ''){
                $where['user_time'] = ['<=', $end_time];
            }
            // 登录时间
            if(isset($login_start_time) && $login_start_time != '' && isset($login_end_time) && $login_end_time != ''){
                $where['user_last_login'] = ['between', [$login_start_time, $login_end_time]];
            }
            if(isset($login_start_time) && $login_start_time != '' && isset($login_end_time) && $login_end_time == ''){
                $where['user_last_login'] = ['>=', $login_start_time];
            }
            if(isset($login_start_time) && $login_start_time == '' && isset($login_end_time) && $login_end_time != ''){
                $where['user_last_login'] = ['<=', $login_end_time];
            }
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::table('up_u_user')
                ->where($where)
                ->count('user_id');
            $lists = Db::table('up_u_user')
                ->field('user_id, user_username, user_phone, user_area_str, user_gender, 
                user_time, user_real_name, user_status, user_last_login')
                ->where($where)
                ->order('user_time desc')
                ->page($Nowpage,$limits)
                ->select();
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        $province = Db::table('up_area')->where('level', 1)->field('district_id, district')->select();
        $this->assign([
            'province' => $province
        ]);
        return $this->fetch();
    }

    /**
     * 用户详情
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function userDetail(){
        $user_id = input('user_id');
        $user = Db::table('up_u_user')
            ->where('user_id', $user_id)
            ->field('user_username, user_image, user_phone, user_gender, user_real_name, user_shop_name, 
            user_time, user_area_str, user_address, user_status, user_big_total_balance, user_big_balance')
            ->find();
        return $this->fetch('', ['user' => $user]);
    }

    /**
     * 编辑用户
     * @return mixed|\think\response\Json
     */
    public function userEdit(){
        $user_id = input('user_id');
        $user = Db::table('up_u_user')->where('user_id', $user_id)
            ->field('user_username, user_image, user_phone, user_gender, user_real_name, user_shop_name, 
            user_address, user_sheng, user_shi, user_qu')
            ->find();
        if(Request::instance()->isPost()){
            $user_image = input('user_image');
            $user_phone = input('user_phone');
            $user_password = input('user_password');
            $user_username = input('user_username');
            $user_gender = input('user_gender');
            $user_shop_name = input('user_shop_name');
            $user_sheng = input('user_sheng');
            $user_shi = input('user_shi');
            $user_qu = input('user_qu');
            $user_address = input('user_address');
            $sheng_name = Db::table('up_area')->where('district_id', $user_sheng)->value('district');
            $shi_name = Db::table('up_area')->where('district_id', $user_shi)->value('district');
            $qu_name = Db::table('up_area')->where('district_id', $user_qu)->value('district');
            $address = Db::table('up_user_address')
                ->where(['addr_user_id' => $user_id, 'addr_from' => 1, 'addr_del' => 1])
                ->field('addr_id')
                ->find();

            $exist = Db::table('up_u_user')
                ->where(['user_phone' => $user_phone, 'user_status' => 1, 'user_id' => ['NEQ', $user_id]])
                ->find();
            if($exist) return json(['code' => 100, 'msg' => '已有相同手机号']);

            $update = [
                'user_phone' => $user_phone,
                'user_username' => $user_username,
                'user_gender' => $user_gender,
                'user_shop_name' => $user_shop_name,
                'user_sheng' => $user_sheng,
                'user_shi' => $user_shi,
                'user_qu' => $user_qu,
                'user_area_str' => $sheng_name . $shi_name . $qu_name,
                'user_address' => $user_address,
                'user_update_time' => date('Y-m-d H:i:s')
            ];
            if(!empty($user_image)) $update['user_image'] = $user_image;
            if(!empty($user_password)){
                $update['user_password'] = md5($user_password);
                $update['user_password_see'] = $user_password;
            }

            Db::startTrans();
            try{
                // 修改用户信息
                Db::table('up_u_user')->where('user_id', $user_id)->update($update);

                // 修改收货地址信息
                if($address){
                    $update_addr = [
                        'addr_user_phone' => $user_phone,
                        'addr_sheng' => $user_sheng,
                        'addr_shi' => $user_shi,
                        'addr_qu' => $user_qu,
                        'addr_address' => $user_address,
                        'addr_updatetime' => date('Y-m-d H:i:s')
                    ];
                    Db::table('up_user_address')->where('addr_id', $address['addr_id'])->update($update_addr);
                }
                Db::commit();
                return json(['code' => 200, 'msg' => '编辑成功']);
            }catch(\Exception $ee){
                Db::rollback();
                return json(['code' => 100, 'msg' => $ee->getMessage()]);
            }
        }

        $province = Db::table('up_area')->where('level', 1)->field('district_id, district')->select();
        $city = Db::table('up_area')->where('pid', $user['user_sheng'])->field('district_id, district')->select();
        $qu = Db::table('up_area')->where('pid', $user['user_shi'])->field('district_id, district')->select();
        $this->assign([
            'user' => $user,
            'user_id' => $user_id,
            'province' => $province,
            'city' => $city,
            'qu' => $qu,
        ]);
        return $this->fetch();
    }

    /**
     * 积分充值
     * @return mixed|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function userBalance(){
        $user_id = input('user_id');
        $user = Db::table('up_u_user')
            ->where('user_id', $user_id)
            ->field('user_big_balance, user_real_name, user_phone')
            ->find();
        if(Request::instance()->isPost()){
            $balance = input('balance');
            $way = input('way');
            $remark = input('remark');

            if($way == 1){
                $price = $balance;
                $desc = '系统增加';
            }else{
                $price = 0 - $balance;
                $desc = '系统扣除';
            }
            if($remark) $desc = $desc . '_' . $remark;

            Db::startTrans();
            try{
                $this->insertBigInte($user_id, $way, $desc, $balance, $user['user_big_balance'], 0);

                Db::table('up_u_user')
                    ->where('user_id', $user_id)
                    ->inc('user_big_total_balance', $price)
                    ->inc('user_big_balance', $price)
                    ->update();

                Db::commit();
                return json(['code' => 200, 'msg' => '充值成功']);
            }catch (\Exception $e){
                Db::rollback();
                return json(['code' => 100, 'msg' => $e->getMessage()]);
            }

        }
        return $this->fetch('', ['user' => $user, 'user_id' => $user_id]);
    }

    /**
     * 启用/冻结
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function changeStatus(){
        $user_id = input('id');
        $user = Db::table('up_u_user')->where('user_id', $user_id)->field('user_status')->find();
        $newStatus = $user['user_status'] == 1 ? 2 : 1;

        $res = Db::table('up_u_user')->where('user_id', $user_id)->setField('user_status', $newStatus);
        if($res){
            return json(['code' => 200, 'msg' => '操作成功']);
        }else{
            return json(['code' => 100, 'msg' => '操作失败']);
        }
    }

    /**
     * 导出
     * @return \think\response\Json
     */
    public function outExcel(){
        set_time_limit(0);
        $user_ids = input('ids');

        $where['user_big_rule'] = 1;
        $where['user_status'] = ['NEQ', 3];
        $where['user_private_worker'] = 1;
        if($user_ids == -1){
            $keyword = trim(input('keyword'), ' '); // 用户ID/手机号/姓名/昵称
            $user_gender = input('user_gender'); // 性别   1 男   2 女   3 未知
            $user_sheng = input('user_sheng');
            $user_shi = input('user_shi');
            $user_qu = input('user_qu');
            $start_time = input('start_time'); // 注册开始时间
            $end_time = input('end_time'); // 注册结束时间
            $login_start_time = input('login_start_time'); // 登录开始时间
            $login_end_time = input('login_end_time'); // 登录结束时间

            // 关键字
            if(isset($keyword) && $keyword != ''){
                $where['user_id|user_phone|user_username|user_real_name'] = ['like', '%' . $keyword . '%'];
            }
            // 性别
            if(isset($user_gender) && $user_gender != ''){
                $where['user_gender'] = $user_gender;
            }
            // 省
            if(isset($user_sheng) && $user_sheng != ''){
                $where['user_sheng'] = $user_sheng;
            }
            // 市
            if(isset($user_shi) && $user_shi != ''){
                $where['user_shi'] = $user_shi;
            }
            // 区
            if(isset($user_qu) && $user_qu != ''){
                $where['user_qu'] = $user_qu;
            }
            // 注册时间
            if(isset($start_time) && $start_time != '' && isset($end_time) && $end_time != ''){
                $where['user_time'] = ['between', [$start_time, $end_time]];
            }
            if(isset($start_time) && $start_time != '' && isset($end_time) && $end_time == ''){
                $where['user_time'] = ['>=', $start_time];
            }
            if(isset($start_time) && $start_time == '' && isset($end_time) && $end_time != ''){
                $where['user_time'] = ['<=', $end_time];
            }
            // 登录时间
            if(isset($login_start_time) && $login_start_time != '' && isset($login_end_time) && $login_end_time != ''){
                $where['user_last_login'] = ['between', [$login_start_time, $login_end_time]];
            }
            if(isset($login_start_time) && $login_start_time != '' && isset($login_end_time) && $login_end_time == ''){
                $where['user_last_login'] = ['>=', $login_start_time];
            }
            if(isset($login_start_time) && $login_start_time == '' && isset($login_end_time) && $login_end_time != ''){
                $where['user_last_login'] = ['<=', $login_end_time];
            }
        }else{
            if($user_ids == '') return json(['code' => 100, 'msg' => '请选择需要导出的数据']);
            $where['user_id'] = ['IN', $user_ids];
        }

        $list = Db::table('up_u_user')
            ->field([
                'user_id',
                'user_username',
                'user_phone',
                'user_area_str',
                'user_gender',
                'user_time',
                'user_real_name',
                'user_status',
                'user_last_login',
                'user_shop_name',
                'user_address',
                'user_big_balance'
            ])
            ->where($where)
            ->select();

        foreach($list as $k => $v){
            // 手机号
            $list[$k]['user_phone'] = "\t" . $v['user_phone'] . "\t";

            // 性别
            switch($v['user_gender']){
                case 1:
                    $list[$k]['user_gender'] = '男';
                    break;
                case 2:
                    $list[$k]['user_gender'] = '女';
                    break;
                case 3:
                    $list[$k]['user_gender'] = '未知';
                    break;
            }
            // 用户状态
            $list[$k]['user_status'] = $v['user_status'] == 1 ? '启用' : '冻结';
        }

        $cellname = [
            ['user_username', '昵称', 15, 'LEFT'],
            ['user_phone', '手机号', 18, 'LEFT'],
            ['user_real_name', '姓名', 15, 'LEFT'],
            ['user_gender', '性别', 10, 'LEFT'],
            ['user_big_balance', '可用积分', 15, 'LEFT'],
            ['user_status', '用户状态', 10, 'LEFT'],
            ['user_area_str', '地区', 40, 'LEFT'],
            ['user_address', '详细地址', 30, 'LEFT'],
            ['user_time', '注册时间', 18, 'LEFT'],
            ['user_last_login', '最后登录时间', 18, 'LEFT'],
            ['user_shop_name', '店铺名称', 20, 'LEFT']
        ];

        $res = exportExcelZhy('家大业大用户', 'Big_member', $cellname, $list);
        return json($res);
    }
}